package com.filebackup.struts.actions;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.filebackup.business.LocalFileService;
import com.filebackup.business.LocalFolderService;
import com.filebackup.vo.Vo;
import com.filebackup.vo.impl.LocalFileVo;
import com.filebackup.vo.impl.LocalFolderVo;
import com.filebackup.vo.impl.SendSyncVo;

public class SendSyncAction extends FilebackupSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private LocalFileService localFileService;
	private LocalFolderService localFolderService;

	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		try {

			List<Vo> folderList = this.getLocalFolderService()
					.findFolderByUser(this.getSessionUser().getId());
			List<Vo> fileList = this.getLocalFileService().findFileByUser(
					this.getSessionUser().getId());
			JSONArray folderArr = new JSONArray();
			JSONArray fileArr = new JSONArray();
			for (int i = 0; i < folderList.size(); i++) {
				SendSyncVo vo = new SendSyncVo();
				vo.setId(((LocalFolderVo) folderList.get(i)).getId());
				vo.setPath(this.getLocalFolderService().returnPath(
						((LocalFolderVo) folderList.get(i)).getId()));
				vo.setVersion(((LocalFolderVo) folderList.get(i)).getVersion());
				folderArr.add(vo);
			}
			JSONObject folderObj = new JSONObject();
			folderObj.put("folder", folderArr);
			for (int i = 0; i < fileList.size(); i++) {
				SendSyncVo vo = new SendSyncVo();
				vo.setId(((LocalFileVo) fileList.get(i)).getId());
				vo.setPath(this.getLocalFileService().returnPath(
						((LocalFileVo) fileList.get(i)).getId()));
				System.out.println("!!!!!!!!!!!!!" + vo.getPath());
				vo.setVersion(((LocalFileVo) fileList.get(i)).getVersion());
				fileArr.add(vo);
			}
			folderObj.put("file", fileArr);
			System.out.println(folderObj.toString());

			response.getWriter().print(folderObj.toString());
			response.flushBuffer();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;

	}

	public void setLocalFileService(LocalFileService localFileService) {
		this.localFileService = localFileService;
	}

	public LocalFileService getLocalFileService() {
		return localFileService;
	}

	public void setLocalFolderService(LocalFolderService localFolderService) {
		this.localFolderService = localFolderService;
	}

	public LocalFolderService getLocalFolderService() {
		return localFolderService;
	}

}
